package com.ptkc.web;

import com.ptkc.constants.WebResult;
import com.ptkc.constants.WebStatus;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.transport.NoNodeAvailableException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: Mr.Jiao
 * @date: 2018年11月07日
 */
@ControllerAdvice
@RestController
@Slf4j
public class ExceptionController {

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public WebResult methodNotSupportHandle(HttpServletRequest request, HttpServletResponse response, HttpRequestMethodNotSupportedException e) {
        return WebResult.fail("不支持的请求方法");
    }

    @ExceptionHandler(value = Exception.class)
    public WebResult defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        System.out.println(req.getServletPath());
        if(e instanceof NoHandlerFoundException){
            return WebResult.fail(WebStatus.SOURCE_NOT_FOUND, "找不到资源路径");
        }else if(e instanceof NoNodeAvailableException){
            return WebResult.fail("搜索引擎连接失败");
        }else{
            e.printStackTrace();
        }
        return WebResult.fail("系统错误");
    }

}
